<template>
  <!-- 表格内容区域 -->
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <h3>{{ tableQuery.title }}</h3>
        <el-button class="button" type="text" v-if="!tableQuery.cz" @click="router.push('/list')">查看全部</el-button>
      </div>
    </template>
    <el-table :data="safeList" style="width: 100%;height: 355px; overflow-y: auto;">
         <!-- 特殊处理EVALRECORD列 -->
      <el-table-column prop="EVALRECORD" label="记录标题" width="150"
        v-if="tableQuery.columns.some(col => col.prop === 'EVALRECORD')">
        <template #default="scope">
            <!-- 这里可以展示JSON中的两块值 -->
            <div class="eval-record-item">
               {{ gscl(scope.row.EVALRECORD, 'first') || '-' }}
            </div>
            <div class="eval-record-item-bottom">
               {{ gscl(scope.row.EVALRECORD, 'content') || '-' }}
            </div>
        </template>
      </el-table-column>

      <el-table-column v-for="item in filteredColumns" :key="item.prop" :prop="item.prop" :label="item.label"
        :width="item.width" />

      <el-table-column label="操作" width="100" v-if="tableQuery.cz">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="handleClick(scope.row)">
            <el-icon>
              <View />
            </el-icon>
          </el-link>
          <!-- <el-link type="primary" :underline="false">
            <el-icon><edit-pen /></el-icon>
          </el-link> -->
          <el-popconfirm confirm-button-text="确定" cancel-button-text="暂时不" :icon="InfoFilled" icon-color="red"
            title="你确定删除吗?" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-link type="danger" :underline="false">
                <el-icon><delete-filled /></el-icon>
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 卡片尾部内容（通过 footer 插槽实现） -->
    <template #footer v-if="tableQuery.small">
      <div class="card-footer">
        <!-- 分页组件 - 添加update:value事件监听 -->
        <DialogPage :value="tableQuery" :refresh="getTableData" @update:value="handleTableQueryUpdate" />
      </div>
    </template>
  </el-card>
</template>

<script setup>
import { ElCard, ElLink } from "element-plus";
import "element-plus/dist/index.css";
import { defineProps, computed, onMounted, defineEmits } from "vue";
import DialogPage from "@/components/DialogPage.vue";
import { useStore } from '@/store';
import  { useRouter } from 'vue-router';
const router = useRouter();
const store = useStore();
const recordStore = store.record;

// 定义属性
const props = defineProps({
  tableQuery: {
    type: Object,
    default: () => ({
      list: [], // 确保默认是数组
      page: 1,
      size: 5,
      total: 0
    })
  }
})


// 定义事件 - 添加update:tableQuery事件
const emit = defineEmits(['delete-item', 'update:tableQuery'])

// 添加计算属性，判断当前选择的学期是否可操作
let isCurrentSemesterOperable = computed(() => {
  // 从store中获取当前选择的学期id
  const semesterId = store.record.semesterid;
  return store.settings.isSemesterOperable(semesterId)
})

// 修改safeList计算属性，使用props传入的list数据
const safeList = computed(() => {
  props.tableQuery.list.forEach(item => {
    item.EVALRECORD = gscl(item.EVALRECORD)
  })
  return props.tableQuery.list || [];
})
const filteredColumns = computed(() => {
  return props.tableQuery.columns.filter(item => item.prop !== 'EVALRECORD')
})

let gscl = (str, returnType) => {
  // 检查输入是否为空或不是字符串
  if (!str || typeof str !== 'string') {
    return str || ''; // 如果为空或不是字符串，直接返回原值或空字符串
  }
  
  try {
    // 尝试解析JSON字符串
    // 首先检查字符串是否以{开头并以}结尾，或者以[开头并以]结尾
    if ((str.startsWith('{') && str.endsWith('}')) || 
        (str.startsWith('[') && str.endsWith(']'))) {
      const obj = JSON.parse(str);
      
      // 如果解析结果是对象
      if (typeof obj == 'object' && obj !== null) {
        // 如果returnType是'content'，优先返回"活动内容"属性
        if (returnType == 'content' && obj.hasOwnProperty('活动内容')) {
          return obj.活动内容;
        }
         if (returnType == 'content' && obj.hasOwnProperty('内容')) {
          return obj.内容;
        }
         if (returnType == 'content' && obj.hasOwnProperty('奖励原因')) {
          return obj.奖励原因;
        }
        // 如果returnType是'first'或者没有"活动内容"属性，返回第一个属性的值
        if (returnType == 'first') {
          const keys = Object.keys(obj);
          if (keys.length > 0) {
            return obj[keys[0]];
          }
        }
      }
    }
    
    // 如果不是有效的JSON对象或数组，直接返回原始字符串
    return str;
  } catch (error) {
    // 静默处理错误，直接返回原始字符串
    return str;
  }
}

// 修改handleDelete方法
const handleDelete = (item) => {
  console.log(item);
    // 检查当前学期是否可操作
    if (!isCurrentSemesterOperable.value) {
      // 不可操作，提示用户
      ElMessage({
        message: '非当前学期，不可删除操作',
        type: 'warning'
      });
      return;
    }
  

  emit('delete-item', item.RECORD_ID);
  // 删除后刷新当前页数据
  if (props.tableQuery.title === '个人经历' && props.tableQuery.cz) {
    recordStore.setListPagePaginatedRecords(props.tableQuery.page, props.tableQuery.size);
  } else {
    recordStore.setPaginatedRecords(props.tableQuery.page, props.tableQuery.size);
  }
}

const handleClick = (row) => {
  emit('row-click', row);
}
// 处理表格查询参数更新
const handleTableQueryUpdate = (newValue) => {
  props.tableQuery.page = newValue.page;
  // props.tableQuery.total = newValue.total;

  // 发出事件通知父组件更新tableQuery
  emit('update:tableQuery', newValue);
}


// 组件挂载时初始化数据
onMounted(() => {
  // 确保有数据
  if (!props.tableQuery.list || props.tableQuery.list.length === 0) {
    recordStore.fetchRecords();
  }
});




</script>

<style scoped lang="scss">
.box-card {
  height: 100%;
  box-shadow: $base-box-shadow;
  border-radius: 10px;

  .el-scrollbar {
    height: 200px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-footer {
    .pagination-demo {
      padding: 0;
    }
  }

  .quick-functions {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    padding: 15px;

    .function-item {
      width: calc(50% - 10px);
      display: flex;
      justify-content: center;
      align-items: center;

      .function-link {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        padding: 15px;
        border-radius: 10px;
        background-color: #f0f2f5;
        width: 100%;
        height: 100%;

        .function-icon {
          font-size: 24px;
          color: $base-color-primary;
          margin-bottom: 10px;
          display: contents;
        }

        .function-text {
          font-size: $base-font-size-default;
          color: $base-color-6;
        }
      }
    }
  }

  ::v-deep .el-table .el-table__body,
  ::v-deep .el-table .el-table__header {
    width: 100% !important;
  }

  .el-link.el-link--primary {
    margin: 0 10px;
  }
}

.eval-record-item {
  font-size: 14px;
  font-weight: 600;
}
.eval-record-item-bottom {
  font-size: 12px;
  color: #999;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}


</style>
